package com.bci.internal.engine.bcibpmengine.utils;


import org.springframework.util.StringUtils;

/**
 * 字符串工具类
 * @author jzwu
 * @since 2021/4/4 0004
 */
public abstract class BCStringUtils extends StringUtils {

    /**
     * 手机号脱敏筛选正则
     */
    private static final String PHONE_BLUR_REGEX = "(\\d{3})\\d{4}(\\d{4})";
    /**
     * 手机号脱敏替换正则
     */
    private static final String PHONE_BLUR_REPLACE_REGEX = "$1****$2";
    /**
     * 邮箱地址脱敏筛选正则
     */
    private static final String EMAIL_BLUR_REGEX = "(\\w+)\\w{3}@(\\w+)";
    /**
     * 邮箱地址脱敏替换正则
     */
    private static final String EMAIL_BLUR_REPLACE_REGEX = "$1***@$2";
    /**
     * 身份证号码脱敏筛选正则
     */
    private static final String IDCARD_CN_BLUR_REGEX = "(?<=\\w{4})\\w(?=\\w{4})";
    /**
     * 身份证号码脱敏替换正则
     */
    private static final String IDCARD_CN_BLUR_REPLACE_REGEX = "*";


    /**
     * 关键信息脱敏
     * 手机号码污染中间四位, 邮箱地址污染@前三位, 其他只保留首尾字符
     *
     * @param info 敏感信息
     * @return 脱敏信息
     */
    public static String blur(String info) {
        if (null == info || info.trim().length() < 3) {
            return info;
        }
        String s = info.trim();
        if (BCValidationUtils.isPhoneNumberLegal(s)) {
            return s.replaceAll(PHONE_BLUR_REGEX, PHONE_BLUR_REPLACE_REGEX);
        }

        if (BCValidationUtils.isChineseIdCardNumberLegal(s)) {
            return s.replaceAll(IDCARD_CN_BLUR_REGEX, IDCARD_CN_BLUR_REPLACE_REGEX);
        }
        char[] chars = s.toCharArray();
        for (int i = 1; i < chars.length - 1; i++) {
            chars[i] = '*';
        }
        return String.valueOf(chars);
    }



    public static boolean containsChinese(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (isChineseCharacter(str.charAt(i))) {
                return true;
            }
        }
        return false;
    }

    public static boolean isAllChinese(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!isChineseCharacter(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean isChineseCharacter(char c) {
        return (c >= 0x4E00 && c <= 0x9FA5) || (c >= 0xF900 && c <= 0xFA2D);
    }
}
